package com.donfelix.looknews.view.activity;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.util.SimpleArrayMap;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.transition.ChangeBounds;
import android.transition.Fade;
import android.transition.Slide;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.view.animation.AnimationUtils;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.donfelix.looknews.R;
import com.donfelix.looknews.common.BaseActivity;
import com.donfelix.looknews.common.LookNewsApplication;
import com.donfelix.looknews.util.AnimUtils;
import com.donfelix.looknews.util.SPUtils;
import com.donfelix.looknews.util.ToastUtil;
import com.donfelix.looknews.util.UIUtils;
import com.donfelix.looknews.util.ViewUtils;
import com.donfelix.looknews.view.fragment.AboutFragment;
import com.donfelix.looknews.view.fragment.MeizhiFragment;
import com.donfelix.looknews.view.fragment.SettingFragment;
import com.donfelix.looknews.view.fragment.TopNewsFragment;
import com.donfelix.looknews.view.fragment.ZhihuFragment;
import com.donfelix.looknews.view.implpresenter.MainPresenterImpl;
import com.donfelix.looknews.view.implview.IMain;
import com.donfelix.looknews.view.presenter.IMainPresenter;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity implements IMain {

    @BindView(R.id.status_bar_background)
    View statusBarBackground;
    @BindView(R.id.fragment_container)
    FrameLayout fragmentContainer;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.nav_view)
    NavigationView navView;
    @BindView(R.id.drawer)
    DrawerLayout drawer;

    private IMainPresenter mainPresenter;
    private int navigationID;
    private MenuItem currentMenuItem;
    private SimpleArrayMap<Integer, String> titleArrayMap = new SimpleArrayMap<>();
    private Fragment currentFragment;
    private SwitchCompat themeSwitch;
    private long exitTime;
    private List<String> titles = new LinkedList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mainPresenter = new MainPresenterImpl(this, this);
        mainPresenter.getBackground();
        toolbar.setOnMenuItemClickListener(menuItemClickListener);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            animateToolbar();
        }
        addFragmentsAndTitle();

        drawer.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

        if (savedInstanceState == null) {
            navigationID = SPUtils.getNevigationItem(this);
            if (navigationID != -1) {
                currentMenuItem = navView.getMenu().findItem(navigationID);
            }
            if (currentMenuItem == null) {
                currentMenuItem = navView.getMenu().findItem(R.id.zhihuitem);
            }
            if (currentMenuItem != null) {
                currentMenuItem.setCheckable(true);
                Fragment fragment = getFragmentByID(currentMenuItem.getItemId());
                String title = titleArrayMap.get(currentMenuItem.getItemId());
                if (fragment != null) {
                    switchFragment(fragment, title);
                }
            }
        } else {
            if (currentMenuItem != null) {
                Fragment fragment = getFragmentByID(currentMenuItem.getItemId());
                String title = titleArrayMap.get(currentMenuItem.getItemId());
                if (fragment != null) {
                    switchFragment(fragment, title);
                }
            } else {
                switchFragment(new ZhihuFragment(), getResources().getString(R.string.zhihu));
                currentMenuItem = navView.getMenu().getItem(R.id.zhihuitem);
            }
        }
        navView.setNavigationItemSelectedListener(navigationItemSelectListener);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            drawer.setOnApplyWindowInsetsListener(applyWindowInsetsListener);
        }

        int[][] state = new int[][]{
                new int[]{-android.R.attr.state_checked},// unchecked
                new int[]{android.R.attr.state_checked} // pressed
        };
        int[] color = new int[]{Color.BLACK, Color.BLACK};
        int[] iconColor = new int[]{Color.GRAY, Color.BLACK};
        navView.setItemTextColor(new ColorStateList(state, color));
        navView.setItemIconTintList(new ColorStateList(state, iconColor));
        //主题变色
        MenuItem item = navView.getMenu().findItem(R.id.nav_theme);
        item.setOnMenuItemClickListener(subMenuItemClickListener);
        themeSwitch = (SwitchCompat) MenuItemCompat.getActionView(item).findViewById(R.id.view_switch);
        themeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                themeSwitch.setChecked(isChecked);
                if (isChecked) {
                    setThemeColor(Color.GREEN);
                } else {
                    setThemeColor(getResources().getColor(R.color.colorPrimaryDark));
                }
            }
        });

        MenuItem setting = navView.getMenu().findItem(R.id.nav_setting);
        setting.setOnMenuItemClickListener(subMenuItemClickListener);
    }

    private void setThemeColor(int color) {
        getWindow().setStatusBarColor(color);
        toolbar.setBackgroundColor(color);
    }

    @Override
    public void getPic(String description) {
        View headerView = navView.getHeaderView(0);
        LinearLayout llImage = (LinearLayout) headerView.findViewById(R.id.slide_image);
        if (new File(getFilesDir().getPath() + "/bg.jpg").exists()) {
            BitmapDrawable drawable = new BitmapDrawable(getResources(), getFilesDir().getPath() + "/bg.jpg");
            llImage.setBackground(drawable);
        }
        TextView desc = (TextView) llImage.findViewById(R.id.image_description);
        if (description != null) {
            desc.setText(description);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private Toolbar.OnMenuItemClickListener menuItemClickListener = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.menu_open:
                    drawer.openDrawer(Gravity.START);
                    break;
                case R.id.menu_about:
                    itemSwitchFragment(item);
                    //goAboutActivity();
                    break;
                default:
                    break;
            }
            return true;
        }
    };

    private MenuItem.OnMenuItemClickListener subMenuItemClickListener = new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.nav_theme:
                    //屏蔽主题的点击事件
                    break;
                case R.id.nav_setting:
                    itemSwitchFragment(item);
                    drawer.closeDrawer(Gravity.START, true);
                    break;
                default:
                    break;
            }
            return true;
        }
    };

    private void itemSwitchFragment(MenuItem item) {
        item.setCheckable(true);
        Fragment fragment = getFragmentByID(item.getItemId());
        String title = titleArrayMap.get(item.getItemId());
        if (fragment != null) {
            switchFragment(fragment, title);
        }
    }

    private NavigationView.OnNavigationItemSelectedListener navigationItemSelectListener =
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    if (currentMenuItem != item && currentMenuItem != null) {
                        currentMenuItem.setCheckable(false);
                        int itemId = item.getItemId();
                        SPUtils.putNevigationItem(MainActivity.this, itemId);
                        currentMenuItem = item;
                        currentMenuItem.setCheckable(true);
                        switchFragment(getFragmentByID(currentMenuItem.getItemId()), titleArrayMap.get(currentMenuItem.getItemId()));
                    }
                    drawer.closeDrawer(Gravity.START, true);
                    return true;
                }
            };

    private View.OnApplyWindowInsetsListener applyWindowInsetsListener =
            new View.OnApplyWindowInsetsListener() {
                @Override
                public WindowInsets onApplyWindowInsets(View view, WindowInsets insets) {
                    // inset the toolbar down by the status bar height
                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) toolbar.getLayoutParams();
                    params.topMargin += insets.getSystemWindowInsetTop();
                    params.rightMargin += insets.getSystemWindowInsetRight();
                    toolbar.setLayoutParams(params);

                    // inset the grid top by statusbar+toolbar & the bottom by the navbar (don't clip)
                    fragmentContainer.setPadding(fragmentContainer.getLeft(),
                            insets.getSystemWindowInsetTop() + ViewUtils.getActionBarSize(MainActivity.this),
                            fragmentContainer.getPaddingRight() + insets.getSystemWindowInsetRight(),// landscape
                            fragmentContainer.getPaddingBottom() + insets.getSystemWindowInsetBottom());

                    // we place a background behind the status bar to combine with it's semi-transparent
                    // color to get the desired appearance.  Set it's height to the status bar height
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) statusBarBackground.getLayoutParams();
                    layoutParams.height = insets.getStableInsetTop();
                    statusBarBackground.setLayoutParams(layoutParams);

                    // inset the filters list for the status bar / navbar
                    // need to set the padding end for landscape case

                    // clear this listener so insets aren't re-applied
                    drawer.setOnApplyWindowInsetsListener(null);
                    return insets.consumeSystemWindowInsets();
                }
            };

    private void goAboutActivity() {
        Intent intent = new Intent(this, AboutActivity.class);
        UIUtils.startActivity(intent);
    }

    private void animateToolbar() {
        View child = toolbar.getChildAt(0);
        if (child != null && child instanceof TextView) {
            TextView title = (TextView) child;
            title.setAlpha(0f);
            title.setScaleX(0.8f);
            title.animate()
                    .alpha(1f)
                    .scaleX(1f)
                    .setStartDelay(500)
                    .setDuration(900)
                    .setInterpolator(AnimUtils.getFastOutSlowInInterpolator(this))
                    .start();
        }
        View amv = toolbar.getChildAt(1);
        if (amv != null && amv instanceof ActionMenuView) {
            ActionMenuView menuView = (ActionMenuView) amv;
            popAnim(menuView.getChildAt(0), 500, 200);//filter
            popAnim(menuView.getChildAt(1), 700, 200);//overflow
        }
    }

    private void popAnim(View view, int startDelay, int duration) {
        if (view != null) {
            view.setAlpha(0f);
            view.setScaleX(0f);
            view.setScaleY(0f);
            view.animate()
                    .alpha(1f)
                    .scaleX(1f)
                    .scaleY(1f)
                    .setStartDelay(startDelay)
                    .setDuration(duration)
                    .setInterpolator(AnimationUtils.loadInterpolator(this, android.R.interpolator.overshoot))
                    .start();
        }
    }

    private void addFragmentsAndTitle() {
        titleArrayMap.put(R.id.zhihuitem, getResources().getString(R.string.zhihu));
        titleArrayMap.put(R.id.topnewsitem, getResources().getString(R.string.topnews));
        titleArrayMap.put(R.id.meiziitem, getResources().getString(R.string.meizi));
        titleArrayMap.put(R.id.nav_setting, getResources().getString(R.string.setting));
        titleArrayMap.put(R.id.menu_about, getResources().getString(R.string.about));
    }

    private Fragment getFragmentByID(int id) {
        Fragment fragment = null;
        switch (id) {
            case R.id.zhihuitem:
                fragment = new ZhihuFragment();
                break;
            case R.id.topnewsitem:
                fragment = new TopNewsFragment();
                break;
            case R.id.meiziitem:
                fragment = new MeizhiFragment();
                break;
            case R.id.nav_setting:
                fragment = new SettingFragment();
                break;
            case R.id.menu_about:
                fragment = new AboutFragment();
                break;
            default:
                break;
        }
        return fragment;
    }

    public void switchFragment(Fragment fragment, String title) {
        if (currentFragment == null
                || !currentFragment.getClass().getName().equals(fragment.getClass().getName())) {
            Fade exitTransition = new Fade(Gravity.LEFT);
            exitTransition.setDuration(250);
            fragment.setExitTransition(exitTransition);
            Slide enterTransition = new Slide(Gravity.RIGHT);
            enterTransition.setDuration(250);
            fragment.setEnterTransition(enterTransition);
            fragment.setSharedElementEnterTransition(new ChangeBounds());
            titles.add(title);
            fragmentContainer.setBackground(null);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, fragment, title)
                    .addToBackStack(title)
                    .commit();
            toolbar.setTitle(title);
            currentFragment = fragment;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                backStack();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) { // backpressed
            if (drawer.isDrawerOpen(Gravity.START)) {
                drawer.closeDrawer(Gravity.START, true);
            }
            backStack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void backStack() {
        int size = titles.size();
        if (size > 0) {
            if (size > 1) {
                String title = titles.get(size - 2);
                toolbar.setTitle(title);
                fragmentContainer.setBackground(null);
            } else {
                toolbar.setTitle(getResources().getString(R.string.app_name));
                fragmentContainer.setBackground(getResources().getDrawable(R.drawable.funny));
            }
            getSupportFragmentManager().popBackStack();
            titles.remove(size - 1);
        } else {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.showToast(this, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                LookNewsApplication.getApplication().quiteApplication();
            }
        }
    }
}
